module.exports = {
    checkCookie($, cookie, username, password) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/equities/treasure/init`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, resp, data) => {
                // console.log('checkCookie data===:' + data);
                const obj = JSON.parse(data)
                if (!obj.user || !obj.user.id) {
                    console.log('cookie 失效。准备登录');
                    this.login($, username, password).then(cookie => {
                        // console.log('aa', cookie);
                        cookie = cookie[0].split(';')[0]
                        $.localStorage.set(`${username}-cookie`, cookie, 'localStorage')
                        console.log('登录成功', cookie);
                        resolve(cookie)
                    })
                } else {
                    resolve(cookie)
                }
            })
        })
    },
    userInfo($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/equities/treasure/init`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, resp, data) => {
                // console.log('userInfo data===:' + data);
                const obj = JSON.parse(data)
                resolve({
                    // 助学宝金额
                    treasureAmount: obj.treasure.amount,
                    // 助学宝未结算手续费
                    totalManagementFee: obj.treasure.totalManagementFee,
                    // 账户可用余额
                    accountUsableAmount: obj.account.usableAmount,
                    // 账户当前全部资产
                    userUserCurrentAmount: obj.user.userCurrentAmount,
                    // 账户绑定微信昵称
                    userWechatNickName: obj.user.wechatNickName,
                });
            })
        })
    },
    login($, username, password) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/login2?username=${username}&password=password_CODE_PW_OPENID_${password}_CODE_PW_OPENID_undefined`,
                headers: { ...$.headers },
            }, (err, resp, data) => {
                const cookie = resp.headers['set-cookie']
                if (cookie) {
                    console.log(username + ' 登录成功 ' + cookie);
                }
                resolve(cookie);
            })
        })
    },
    // 查询盲盒信息
    boaInfo($, cookie) {
        return new Promise(resolve => {
            $.get({
                url: $.baseUrl + `/userBlindBox/myUserIeaDerBoardStatic`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, resp, data) => {
                const items = JSON.parse(data).items;
                resolve(items)
            })
        })
    },
    // 查询盲盒列表
    boxList($, cookie) {
        return new Promise(resolve => {
            $.get({
                url: $.baseUrl + `/userBlindBox/queryMyUserIeaDerBoard?state=0&page=1`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                const data = JSON.parse(resp).items.data;
                resolve(data)
            })
        })
    },
    // 查询拉新赛列表
    dungList($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/equitiesDungeonUser/list`,
                body: JSON.stringify({
                    aliveState: 0,
                    page: 1,
                    pageSize: 10
                }),
                headers: { ...$.headers, 'Cookie': cookie },
            }, (err, res, resp) => {
                let data = JSON.parse(resp).items.data
                // console.log('dungList', data);
                data = data.map(item => ({
                    id: item.id,
                    name: item.name,
                    // 是否参与
                    canAccept: item.canAccept,
                }))
                resolve(data)
            })
        })
    },
    // 拉力赛参与
    dungAccept($, cookie, id) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/equitiesDungeonUser/accept`,
                body: `id=${id}`,
                headers: { ...$.headers, 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': cookie },
            }, async (err, res, resp) => {
                resolve(resp)
            })
        })
    },
    // 战队信息
    belongInfo($, cookie) {
        return new Promise(resolve => {
            $.get({
                url: $.baseUrl + `/equitiesCompetitionTeam/getBelongsToTeam`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                let data = JSON.parse(resp).items || {
                    teamName: '无',
                    wechatNickName: '无'
                }
                // console.log('dungList', data);
                data = {
                    teamName: data.teamName,
                    wechatNickName: data.wechatNickName
                }
                resolve(data)
            })
        })
    },
    // 获取优惠卷信息
    couponsList($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/points/deduction/findCoupons`,
                body: JSON.stringify({
                    page: 1,
                    pageSize: 300,
                    state: 0, // 0 = 可用 2 = 已使用
                    type: 2 // 2 = 返现卷
                }),
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                // console.log('couponsList', resp);
                let data = JSON.parse(resp).data
                data = data.map(item => ({
                    id: item.id,
                    createdDate: item.createdDate,
                    amount: item.amount,
                    useCondition: item.useCondition,
                    note: item.note,
                    typeString: item.typeString,
                }))
                resolve(data)
            })
        })
    },
    // 开盲盒
    useBox($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/userBlindBox/useIeaDerBoard`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                let data = JSON.parse(resp).items || {}
                resolve(data)
            })
        })
    },
    // 查询基本财富 鸿利金
    getSummary($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/uiweb/invest/summary/querySummary`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                let data = JSON.parse(resp).items || {}
                resolve(data)
            })
        })
    },
    // 查询是否可开盲盒 （查看公开开盲盒情况）
    isBoxList($, cookie) {
        return new Promise(async resolve => {
            $.get({
                url: $.baseUrl + `/ieaDerBoard/queryWinTheLotteryList`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                // console.log('resp===:', resp)
                const data = JSON.parse(resp)
                const is = data.items[0].awardName.includes('懒人加息')
                // const is = true
                resolve(is)
                // const resStr = JSON.stringify(JSON.parse(data), null, 2)
                // if(is) {
                //     notify.sendNotify(`助学盲盒可抽`, 'http://quanyi.hxjx360.com/api/ieaDerBoard/queryWinTheLotteryList   ' + resStr)
                // }
            })
        })
    },
    sign($, cookie, localDateStr = new Date().toLocaleDateString().replaceAll('/', '-')) {
        return new Promise(resolve => {
            console.log(cookie);
            $.post({
                url: $.baseUrl + `/active/getAward`,
                method: 'POST',
                body: `date=${localDateStr}`,
                headers: { ...$.headers, 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': cookie },
            }, async (err, res, resp) => {
                // console.log('sign resp===:' + resp);
                const data = JSON.parse(resp)
                resolve(data)
            })
        })
    },
    // 购买
    buy($, cookie, id, chosenCouponId) {
        return new Promise(resolve => {
            const id2Awards = {}
            id2Awards[id] = '0'
            const data = {
                selectAmount: 0, // 选择金额 不用管
                novice: false, // 是否新手权益
                onLine: false, // 是否在线支付
                weChatPay: false, // 是否微信支付
                id2Awards: id2Awards,
                ids: [id],
                // 可调整参数
                chosenCouponId: chosenCouponId, // 优惠卷
            }
            // console.log('购买data', data, Date.now())
            $.post({
                url: $.baseUrl + `/uiweb/equities/buy`,
                method: 'POST',
                body: JSON.stringify(data),
                headers: { ...$.headers, 'Cookie': cookie },
            }, (err, res, resp) => {
                // console.log('购买resp===:' + resp, Date.now())
                const data2 = JSON.parse(resp)
                resolve(data2)
            })
        })
    },
    // 新权益列表
    equitiesList($, cookie, size = 5, day = 30) {
        return new Promise(resolve => {
            const startDeadLine = this.addDate(0);
            const endDeadLine = this.addDate(day);
            console.log('抢购日期范围', startDeadLine + " ~ " + endDeadLine);
            console.log('抢购执行-数量', size, '天数', day);
            const data = {
                corporationIds: [], // 机构筛选
                page: 1,  // 页码
                direct: false, // 是否专属权益
                novice: false, // 是否新手权益
                type: null, // 权益类型 null全部 0普通 1奖励 999活动
                startDeadLine, // 贴现开始时间
                sortType: 1,
                sortValue: "deadLine",
                // 可调整参数
                pageSize: size, // 一页查几个权益
                endDeadLine, // 贴现结束时间
            }
            // console.log('抢购data', data);
            $.post({
                url: $.baseUrl + `/uiweb/equities/list`,
                method: 'POST',
                body: JSON.stringify(data),
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                console.log('抢购resp===:' + resp);
                const obj = JSON.parse(resp)
                const list = obj.items && obj.items.data.map(item => ({
                    id: item.id,
                    '金额': item.amount,
                    //'createdDate(创建时间)': item.createdDate,
                    //'lastModifiedDate(最后修改时间)': item.lastModifiedDate,
                    '发布时间': item.publishDate,
                    '收益': item.expectedEarnings,
                    //'贴现时间': item.deadLine,
                    '贴现天数': parseInt(((new Date(item.deadLine) - new Date()) / 60 / 60 / 24 / 1000)),
                    '机构': item.corporationName,
                    '用户': item.loanUserName,
                    'WG占用金额': item.occupyDepositAmount,
                    'WG服务金': item.serviceCharge,
                    'WG服务比': item.serviceChargeRate,
                })) || []
                const log1 = `抢购data===: ${list.length} 个权益可抢购！`
                console.log(Date.now() + '-' + log1);
                resolve(list)
            })
        })
    },
    // 转入
    inAmount($, cookie, cacheNum) {
        return new Promise(async resolve => {
            if(!cacheNum) {
                console.log('in 值为 0。结束' + cacheNum)
                resolve('in 值为 0。结束' + cacheNum)
                return
            }
            const { accountUsableAmount } = await this.userInfo($, cookie)
            let num = accountUsableAmount
            if(cacheNum > 0) {
                num = accountUsableAmount - cacheNum
                if(num <= 0) {
                    console.log('余额低于保留金额。结束' + num)
                    resolve('余额低于保留金额。结束' + num)
                    return
                }
            }
            if(num == 0) {
                console.log('金额 0。结束' + num)
                resolve('金额 0。结束' + num)
                return
            }
            console.log('助学宝转出到余额', cookie, num)
            $.post({
                url: $.baseUrl + `/equities/treasure/transfer`,
                method: 'POST',
                body: `amount=${num}`,
                headers: { ...$.headers, 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': cookie },
            }, async (err, resp, data) => {
                resolve(data + '金额：' + num)
            })
        })
    },
    // 转出
    outAmount($, cookie, out) {
        return new Promise(async resolve => {
            if(!out) {
                console.log('out 值为 0。结束' + out)
                resolve('out 值为 0。结束' + out)
                return
            }
            const { treasureAmount, totalManagementFee } = await this.userInfo($, cookie)
            let num = Math.floor((treasureAmount - totalManagementFee) * 100) / 100;
            if(out == -1) {
                // 全部转出，最高 2W
                if(num > 20000) { num = 20000 }
            }
            if(num == 0) {
                console.log('金额 0。结束' + num)
                resolve('金额 0。结束' + num)
                return
            }
            console.log('助学宝转出到余额', cookie, num)
            $.post({
                url: $.baseUrl + `/equities/treasure/expend`,
                method: 'POST',
                body: `amount=${num}`,
                headers: { ...$.headers, 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': cookie },
            }, async (err, resp, data) => {
                resolve(data + '金额：' + num)
            })
        })
    },
    // 查询基本财富 鸿利金
    queryRealName($, cookie) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/uiWeb/realName/authentication/queryRealName`,
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                let data = JSON.parse(resp).items || {}
                resolve(data)
            })
        })
    },
    // 查询已收权益
    bidList($, cookie, page = 1) {
        return new Promise(resolve => {
            $.post({
                url: $.baseUrl + `/uiweb/bid/list`,
                body: JSON.stringify({
                    page: page,
                    // 固定 5 不支持调整
                    pageSize: 5,
                    state: 1, // null全部 0待收 1已收 2逾期 3转卖 
                    order: "buyDate-2"
                }),
                headers: { ...$.headers, 'Cookie': cookie },
            }, async (err, res, resp) => {
                // console.log('resp', resp);
                let data = JSON.parse(resp).items || {data: [], rows: 0}
                resolve(data)
            })
        })
    },
    // 休眠 1 秒
    // await sleep(1000)
    sleep(delay) {
        return new Promise((resolve) => {
            setTimeout(resolve, delay)
        })
    },
    // 当前日期
    currDate(d = new Date()) {
        return d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1) + '-' + (d.getDate() < 10 ? '0' + (d.getDate()) : d.getDate())
    },
    // + n 天
    addDate(n) {
        const d = new Date()
        d.setDate(d.getDate() + n); // 日
        return this.currDate(d)
    }
}